<template>
  <div style="position:relative;">
    <Portal to="right-disable"
            v-loading="infoLoading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <div class="cardHeader"  style="display:flex;">
        <span class="cardTitle">{{$t('custom.component.gadget.botDetail')}}</span>
        <div v-only-clone="botDetail" style="display:flex;margin-left: 50px;">
          <div style="display:flex;margin-left: 20px;align-items: center;">
            <div style="width:36px;height:20px"
                @click.stop="">
              <el-switch @change="changeSwitch($event,botDetailInfo,'enable','detailInfo')"
                        v-model="botDetailInfo.enable"
                        :disabled="!$hasPermission('sys:bots:switch')"
                        ref="enable"
                        v-loading="botDetailInfo.cardEnableLoading"
                        active-color="#17B3A3"
                        inactive-color="#BFBFBF">
              </el-switch>
            </div>
            <span style="color:#7F7F7FFF;margin-left:10px">{{$t('custom.component.viewComponent.trigger')}}</span>
          </div>
          <div style="display:flex;margin-left: 20px;align-items: center;">
            <div style="width:36px;height:20px"
                @click.stop="">
              <el-switch @change="changeSwitch($event,botDetailInfo,'alert','detailInfo')"
                       :disabled="!botDetailInfo.enable||!$hasPermission('sys:bots:switch')"
                        v-model="botDetailInfo.alert"
                        v-loading="botDetailInfo.cardAlertLoading"
                        active-color="#17B3A3"
                        ref="alert"
                        inactive-color="#BFBFBF">
              </el-switch>
            </div>
            <span style="color:#7F7F7FFF;margin-left:10px">{{$t('custom.component.viewComponent.alert')}}</span>
          </div>
          <div style="display:flex;margin-left: 20px;align-items: center;">
            <div style="width:36px;height:20px"
                @click.stop="">
              <el-switch @change="changeSwitch($event,botDetailInfo,'escalation','detailInfo')"
                        v-model="botDetailInfo.escalation"
                        v-loading="botDetailInfo.cardEscalationLoading"
                        active-color="#17B3A3"
                        :disabled="!botDetailInfo.enable || !botDetailInfo.alert||!$hasPermission('sys:bots:switch')"
                        inactive-color="#BFBFBF">
              </el-switch>
            </div>
            <span style="color:#7F7F7FFF;margin-left:10px">{{$t('custom.component.viewComponent.escalate')}}</span>
          </div>
        </div>
      </div>
      <div class="control-section">
        <div class="content-wrapper">
          <template v-if="isEditMode">
            <div class="title">{{$t('custom.component.gadget.botName')}}</div>
            <el-input v-model="botDetailInfo.name"
                      @change="validatePass"
                      size="mini"></el-input>
            <div v-if="editStatus" class="edit_status_botdetail">{{editStatus}}</div>
            <div class="title">{{$t('custom.component.gadget.description')}}</div>
            <el-input v-model="botDetailInfo.description"
                      size="mini"
                      type="textarea"
                      resize='none'
                      :rows="2"></el-input>
          </template>
          <template v-else>
            <div class="title">
              <div>{{$t('custom.component.gadget.botName')}}</div>
            </div>
            <div class="title-value">{{ botDetailInfo.name }}</div>
            <div class="title">{{$t('custom.component.gadget.description')}}</div>
            <div class="title-value">{{ botDetailInfo.description }}</div>
          </template>
        </div>
      </div>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />
    <template v-if="!isEditMode">
      <el-tooltip v-only-clone="$store.getters.botDetail" :open-delay="1000" content="Edit" v-if="$hasPermission('sys:bots:edit')"
                  placement="top">
        <i class="cuifont icon_edit"
           @click="isEditMode = !isEditMode"></i>
      </el-tooltip>
    </template>
    <template v-else>
      <el-tooltip :open-delay="1000" content="Cancel"
                  placement="top">
        <i class="cuifont icon_dismiss"
           @click="cancelEditBotInfo"></i>
      </el-tooltip>
      <el-tooltip :open-delay="1000" content="Update"
                  placement="top">
        <i class="cuifont icon_save"
           @click="updateBotInfo"></i>
      </el-tooltip>
    </template>
  </div>
</template>

<script>
import {checkBotName,updateBot} from '@/api/new'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinChangeSwitch from '@/views/modules/mspbots/bots-bak/my-bots/BotFormatComponents/ChangeSwitch'
import { LinkComponent } from '@/views/modules/mspbots/bots-bak/my-bots/BotFormatComponents/LinkComponent.js'
export default {
  mixins: [mixinGadgetViewModule, mixinChangeSwitch],
  components: { model: () => import('@/components/gadget/query-model/query-model') },
  data () {
    return {
      gadgetSetting: {},
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      dataList: [],
      infoLoading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'customizedbotdetailinfogadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'customizedbotdetailinfogadget' }).gadgetSetting
        }
      },
      queryId: '',
      widgetName: '',
      botDetailSlicer: {},
      botDetailInfo: {},
      originBotInfo: null,
      isEditMode: false,
      editStatus: '',
      load: false,
      botDetail: this.$store.getters.botDetail
    }
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    LinkComponent.$on('changeSwitchHanderInfo', () => {
      this.getQureAll()
    })
    this.botDetail.hide = true
    this.getQureAll()
    // this.query()
    this.subscribeMessage('runReport', this.getQureAll)
    this.$store.state.isWidget = false
    this.gadgetMessageBus.$on(this.pageId + 'botDetailReload', () => {
      // this.getQureAll()
      setTimeout(() => {
        this.getQureAll()
      }, 500)
    })
  },
  destroyed () {
    LinkComponent.$off('changeSwitchHanderInfo')
    this.gadgetMessageBus.$off(this.pageId + 'botDetailReload')
  },
  computed: {
    comDataList () {
      var _self = this
      var retdata = _self.dataList
      return retdata
    }
  },
  watch: {
    isEditMode (val) {
      if (val) {
        this.originBotInfo = this._.cloneDeep(this.botDetailInfo)
      } else {
        this.originBotInfo = null
      }
    }

  },
  methods: {
    handleChangeEnable (e, item) {
      this.changeSwitch(e, item, 'enable')
      if (!item.enable && item.alert) {
        this.changeSwitch(false, item, 'alert')
        item.alert = false
      }
    },
    validatePass () {
      let params = {
        name: this.botDetailInfo.name,
        id: this.botDetailInfo.id ? this.botDetailInfo.id : ''
      }
      checkBotName(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.editStatus = res.msg
            return
          }
          this.editStatus = ''
        })
    },
    saveGadgetSetting () { },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.getQureAll()
    },
    queryModelPreview () {
      this.getQureAll()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = newH * 20 - this.heightoffset - 15
      this.gadgetWidth = newWPx
    },
    query () {
      if(!this.botDetailSlicer.botId) return
      this.editStatus = ''
      this.infoLoading = true
      this.$interface.botStore.getTenantBotInfoApi({ id: this.botDetailSlicer.botId,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.infoLoading = false
            this.$root.eventBus.$emit('ladingBus', this.infoLoading)
            return this.$message.error(res.msg)
          }
          if (res.data && !res.data.isPermission && res.data.isPermission !== undefined) {
            this.$router.replace({ name: '404' })
            return
          }
          this.$store.dispatch('setBotDetail', res.data)
          let temp = {}
          temp = {
            ...res.data,
            cardAlertLoading: false,
            cardEnableLoading: false,
            cardEscalationLoading: false
          }
          this.botDetailInfo = temp
          localStorage.setItem('botnamefordetailpage', res.data.name)
          this.publishMessage('changeBotName')
          this.infoLoading = false
          this.$root.eventBus.$emit('ladingBus', this.infoLoading)
        })
        .catch(() => {
          this.infoLoading = false
          this.$root.eventBus.$emit('ladingBus')
        })
    },
    getQureAll () {
      try {
        let hasQure = window.location.search.split('?').length > 1
        hasQure && window.location.search.split('?')[1].split('&').map(e => {
          this.$set(this.botDetailSlicer, e.split('=')[0], e.split('=')[1])
        })
        if (this.botDetailSlicer.originalId) {
          this.getBotIdByOriginalId(this.botDetailSlicer.originalId)
        } else {
          this.query()
        }
      } catch (error) { }
    },
    updateBotInfo () {
      if (!this.botDetailInfo.name) {
        this.editStatus = 'Required field cannot be empty'
        return
      }
      if (this.editStatus) return false
      this.infoLoading = true
      const params = {
        ...this.botDetailInfo
      }
      updateBot(params)
        .then(({ data: res }) => {
          this.infoLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$store.state.contentTabs.forEach(item => { if (item.menuId === res.data.id) {
            // this.$store.state.contentTabsActiveName=res.data.name
            item.title = res.data.name
            item.name = res.data.name
            item.query.name = res.data.name
            } })
          this.$message.success(res.msg)
          this.isEditMode = false
          this.query()
        })
        .catch((res) => {
          this.$message.error(res)
          this.infoLoading = false
        })
    },
    cancelEditBotInfo () {
      this.botDetailInfo = this._.cloneDeep(this.originBotInfo)
      this.isEditMode = false
    },
    getBotIdByOriginalId (originalId) {
      this.$interface.bots.getBotIdByOriginalId(originalId)
        .then(({ data: res }) => {
          this.$set(this.botDetailSlicer, 'botId', res.data)
          this.query()
        })
        .catch(() => { })
    }
  }
}
</script>
<style scoped lang='scss'>
.cardTitle {
  font-size: 16px;
  color: #404040;
  font-weight: 700;
  line-height: 24px;
}
.title {
  font-size: 14px;
  color: #808080;
  line-height: 20px;
  &-value {
    font-size: 16px;
    color: #404040;
    line-height: 24px;
  }
}
.cuifont {
  position: absolute;
  right: 0;
  top: 0;
  cursor: pointer;
  font-size: 14px;
  padding: 7px;
  border-radius: 4px;
  &:hover {
    background-color: $--theme-color-background;
    color: $--theme-color;
  }
}
.icon_dismiss {
  right: 30px;
}
.edit_status_botdetail{
  color: #F56C6C;
  font-size: 12px;
  padding-top: 4px;
}
</style>
